<?php

namespace Frieza\Modules\Weekly\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Vote\Vote;
use Doraemon\model\Weekly\Weekly;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Timer;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class WeeklyController extends Controller
{

    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', 20);

        return $content
            ->header('周报列表')
            ->breadcrumb(
                [
                    'text' => '周报列表配置页',
                    'url' => '/weekly/index'
                ]
            )
            ->body(self::listAction($params));
    }


    private function listAction($params = [])
    {
        $nextTimeStartEnd = Timer::getWeekStartAndEnd(strtotime(date('Y-m-d H:i:s') . " +7 days"));
        $data = Weekly::select('*', ['ORDER' => ['start_time' => 'DESC']]);
        if (empty($data)) {
            $data[0]['id'] = 0;
            $data[0]['week'] = $nextTimeStartEnd['start_time'] . '~~~' . $nextTimeStartEnd['end_time'];
            $data[0]['state'] = '待配置';
            $data[0]['edittime'] = '';
            $data[0]['admin_id'] = '';
        } else {
            foreach ($data as &$v) {
                $v['week'] = $v['start_time'] . '~~~' . $v['end_time'];
                if (strtotime($v['start_time']) < strtotime(date('Y-m-d H:i:s')) && strtotime($v['end_time']) > strtotime(date('Y-m-d H:i:s'))) {
                    // 进行中
                    $v['state'] = '进行中';
                } elseif (strtotime($v['start_time']) > strtotime(date('Y-m-d H:i:s'))) {
                    // 准备中
                    $v['state'] = '准备中';
                } else if (strtotime($v['end_time']) < strtotime(date('Y-m-d H:i:s'))) {
                    // 已完成
                    $v['state'] = '已完成';
                }
            }
            // 判断下周模板是否编辑过
            $timeStartEnd = Timer::getWeekStartAndEnd();

            if ($data[0]['start_time'] != $nextTimeStartEnd['start_time']) {
                $temp['id'] = 0;
                $temp['week'] = $nextTimeStartEnd['start_time'] . '~~~' . $nextTimeStartEnd['end_time'];
                $temp['state'] = '待配置';
                $temp['edittime'] = '';
                $temp['admin_id'] = '';
                array_unshift($data, $temp);
            }

        }

        $gridModel = new pGridDataModel($data, count($data), []);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->disableRowSelector();

            $grid->paginate(20);
            $grid->column('id')->hide();
            $grid->column('week', '周报期数');

            $grid->column('state', '状态');
            $grid->column('edittime', '更新时间');

            $grid->column('admin_id', '最后操作人')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($actions->row->state == '已完成') {
                    $actions->prepend('<a class="fa reload-data fa-eye" href="/admin/weekly/index/' . $actions->row->id . '" >查看</a>');
                } else {
                    $actions->prepend('<a class="fa reload-data fa-cubes" href="/admin/weekly/index/' . $actions->row->id . '/edit" >配置</a>');
                }

            });
        });

        return $listGrid;
    }

    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑配置页';
        } else {
            $title = '创建配置页';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('周报配置页')
            ->breadcrumb(
                [
                    'text' => '配置列表',
                    'url' => '/weekly/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {
        if ($id > 0) {
            $data = Weekly::get('*', ['id' => $id]);
            $data['link'] = [
                "link_type" => $data['link_type'],
                "link_params" => $data['link_params']
            ];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->text('topic_ids', '话题ids')->required('必填')->placeholder('多个用"英文逗号"分隔');
        $form->text('module_name', '活动模块名称')->required('必填');
        $form->text('title', '活动标题')->required('必填');
        $form->textarea('description', '活动描述')->required('必填');
        $form->text('btn_info', '按钮文案')->required('必填');
        $form->linkSelect('link', '按钮链接');
        $form->imgUpload('pic_id', '引导插画', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);

        $form->action('/admin/weekly/index/save');

        return $form;
    }

    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        if (strpos($params['topic_ids'], '，') != false) {
            $error = new MessageBag([
                'title' => '保存失败, 话题ids含有中文逗号'
            ]);
            return back()->with(compact('error'));
        }
        $data = [
            'topic_ids' => $params['topic_ids'],
            'module_name' => $params['module_name'],
            'title' => $params['title'],
            'pic_id' => $params['pic_id'],
            'description' => $params['description'],
            'btn_info' => $params['btn_info'],
            'link_type' => $params['link_type'],
            'link_params' => json_encode($params['link_params'], JSON_UNESCAPED_UNICODE),
            'admin_id' => Admin::user()->id,
        ];

        if (isset($params['id']) && $params['id']) {
            //编辑
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = Weekly::update($data, ['id' => $params['id']]);

        } else {
            //创建
            $nextTimeStartEnd = Timer::getWeekStartAndEnd(strtotime(date('Y-m-d H:i:s') . " +6 days"));
            $data['start_time'] = $nextTimeStartEnd['start_time'];
            $data['end_time'] = $nextTimeStartEnd['end_time'];
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = Weekly::insert($data);
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/weekly/index')->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function check(Content $content, $id = 0)
    {
        $data = Weekly::get('*', ['id' => $id]);
        $data['link'] = [
            "link_type" => $data['link_type'],
            "link_params" => $data['link_params']
        ];
        $form = new Form($data);
        $form->text('topic_ids', '话题ids')->required('必填')->placeholder('多个用"英文逗号"分隔')->readonly();
        $form->text('module_name', '活动模块名称')->required('必填')->readonly();
        $form->text('title', '活动标题')->required('必填')->readonly();
        $form->textarea('description', '活动描述')->required('必填')->readonly();
        $form->text('btn_info', '按钮文案')->required('必填')->readonly();
        $form->linkSelect('link', '按钮链接')->readonly();
        $form->imgUpload('pic_id', '引导插画', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])->readonly();
        $form->disableReset();
        $form->disableSubmit();
        $desc = '';
        $content->row($form);
        return $content
            ->header('配置详情')
            ->description($desc);
    }
}
